package hu.jonas.time.server;

import hu.jonas.time.client.ProjectService;
import hu.jonas.time.client.model.Project;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class ProjectServiceImpl extends RemoteServiceServlet implements	ProjectService {

	private static Logger logger = Logger.getLogger(ProjectServiceImpl.class.getName());
	
	@Override
	public Project getProjectByName(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Project> getProjects() {
		
		PersistenceManager pm = PersistenceManagerHolder.get().getPersistenceManager();
		
		try {
			List<Project> result = (List<Project>) pm.newQuery(Project.class).execute();
			
			logger.info("Got the list of projects");
			
			List<Project> projects = new ArrayList<Project>();
			projects.addAll(pm.detachCopyAll(result));
			
			for (Project p : projects) {
				logger.info(p.toString());
			}
			
			return projects;
			
		} finally {
			pm.close();
		}
	}

	@Override
	public long createProject(String name, Date dueDate) {
		
		PersistenceManager pm = PersistenceManagerHolder.get().getPersistenceManager();

		try {
			Project project = new Project();
			
			project.setName(name);
			project.setDueDate(dueDate);
			
			project = pm.makePersistent(project);
			
			logger.info("Project is created, key is " + project.getKeyId());
			
			return project.getKeyId();
			
		} finally {
			pm.close();
		}
	}

}
